package com.jinly.ryder.database.web;

import com.alibaba.fastjson.JSON;
import com.jinly.ryder.account.web.utils.AuthUtil;
import com.jinly.ryder.common.auth.model.AuthRole;
import com.jinly.ryder.common.auth.model.AuthType;
import com.jinly.ryder.database.service.DatabaseExecService;
import com.jinly.ryder.database.service.model.QueryParam;
import com.jinly.ryder.database.service.model.QueryResult;
import com.jinly.ryder.manage.service.DatabaseInstanceService;
import com.jinly.ryder.manage.service.model.DatabaseInstance;
import com.jinly.ryder.manage.web.mapping.DatabaseInstanceVOMapping;
import com.jinly.ryder.manage.web.vo.DatabaseInstanceVO;
import lombok.RequiredArgsConstructor;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("database")
@RequiredArgsConstructor
public class DatabaseQueryController {

    private final DatabaseExecService databaseExecService;
    private final DatabaseInstanceService databaseInstanceService;
    private final DatabaseInstanceVOMapping databaseInstanceVOMapping;

    @PostMapping("execQuery")
    public QueryResult execQuery(@RequestBody QueryParam param) {
        DatabaseInstance instance = databaseInstanceService.get(param.getInstanceId());
        Assert.notNull(instance, "实例不存在");
        AuthUtil.check(AuthType.APP, instance.getAppName(), AuthRole.TESTER);
        if (param.getPageNo() == null || param.getPageNo() == 0L) {
            param.setPageNo(1L);
        }
        if (param.getPageSize() == null || param.getPageSize() == 0L || param.getPageSize() > 100) {
            param.setPageSize(10L);
        }
        param.setSql(param.getSql().trim());
        QueryResult r = databaseExecService.execQuerySql(instance, param);
        System.out.println(JSON.toJSONString(r));
        return r;
    }

    @PostMapping("test")
    public Boolean test(@RequestBody DatabaseInstanceVO instance) {
        AuthUtil.check(AuthType.APP, instance.getAppName(), AuthRole.TESTER);
        return databaseExecService.testConnection(databaseInstanceVOMapping.toModel(instance));
    }
}
